<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Login Tests</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" type="text/css" href="static/splunkjs/css/bootstrap.css"/>
    <style type="text/css">
        .fail{
            color: red;
        }
        .main-area {
            padding: 30px;
        }
    </style>
</head>

<body>
    <div class="main-area">
        <h2>Login Form</h2>
        <p>This page tests login and authentication. When you enter a
            name and password, these credentials are used to log in
            to Splunk.</p>
        <p>If login is successful, a session key is returned and stored
            in a cookie, along with the username.</p>
        <br>
        <p><b>Username:</b></p>
        <input id="usernamebox" type="text" value="admin">
        <p><b>Password:</b></p>
        <input id="pwbox" type="password" value="changeme">
        <br>
        <button class="btn" onclick="onLogin()">Log in</button>
        <br>
        <div id="errorText"></div>
    </div>

    <script src="static/splunkjs/config.js"></script>

    <script>
        require.config({
            baseUrl: "static/"
        });

        function onLogin() {
            require([
                "jquery",
                "splunkjs/splunk",
            ], function($, jssdk) {
                // Get the username and passwords
                var username = $("#usernamebox").val();
                var password = $("#pwbox").val();

                // Use the Splunk SDK for JavaScript to log in to Splunk

                // Create a Service object
                var http =  new jssdk.ProxyHttp("/proxy");
                var service = new jssdk.Service(http, {
                    username: username,
                    password: password,
                    scheme: "https",
                    host: "localhost",
                    port: 8089
                });

                // Log in to Splunk
                service.login(function(err) {
                    // The session key and username are required for logging in
                    if (!err) {
                        var key = service.sessionKey;
                        // Save the session key and username in cookies
                        $.cookie("splunk_sessionkey", key);
                        $.cookie("splunk_username", username);
                    }
                    else {
                        $("#errorText").empty().append("<p class='fail'><br>Login failed! See the console for error info.</p>");
                        console.error("Login failed: ", err);
                    }
                });
            });
        }
    </script>
</body>
</html>
